package main

import (
	"fmt"
	"bufio"
	"os"
	"net"
	"io"
	"deploy-ms/utils"

)



func Client() {
	fmt.Println("send ur file to the destination", "input ur filename:")
	reader := bufio.NewReader(os.Stdin)
	input, _, _ := reader.ReadLine()
	fmt.Println(string(input))
	file, err := os.Open(string(input))
	if err != nil {
		panic(err)
	}
	defer file.Close()
	fileinfo, err := file.Stat()
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		fmt.Println(utils.StrToGBK("connect server fail！"), utils.StrToGBK(err.Error()))
		return
	}
	defer conn.Close()

	//send filename
	_, err = conn.Write([]byte(fileinfo.Name()))
	if err != nil {
		fmt.Println("conn.Write", err.Error())
	}
	//send file size
	_, err = conn.Write(utils.Int64ToBytes(fileinfo.Size()))
	if err != nil {
		fmt.Println("conn.Write", err.Error())
	}

	buff := make([]byte, 1024)
	count := 0
	for {
		n, err := file.Read(buff)
		if err != nil && err != io.EOF {
			panic(err)
		}
		if n == 0 {
			conn.Write([]byte("filerecvend"))
			fmt.Println("filerecvend")
			break
		}
		fmt.Println(count,len(buff),buff)
		_, err = conn.Write(buff)
		if err != nil {
			fmt.Println(err.Error())
		}
		count++
	}
}
func main() {
	utils.InitServerConfig()
	Client()
}
